/*
设置菜单滑动
*/
$(function() {
    $('#side-menu').metisMenu();
});

//Loads the correct sidebar on window load,
//collapses the sidebar on window resize.
// Sets the min-height of #page-wrapper to window size
$(function() {
    $(window).bind("load resize", function() {
        topOffset = 50;
        width = (this.window.innerWidth > 0) ? this.window.innerWidth : this.screen.width;
        if (width < 768) {
            $('div.navbar-collapse').addClass('collapse');
            topOffset = 100; // 2-row-menu
        } else {
            $('div.navbar-collapse').removeClass('collapse');
        }

        height = ((this.window.innerHeight > 0) ? this.window.innerHeight : this.screen.height) - 1;
        height = height - topOffset;
        if (height < 1) height = 1;
        if (height > topOffset) {
            $("#page-wrapper").css("min-height", (height) + "px");
        }
    });

    var url = window.location;
    var element = $('ul.nav a').filter(function() {
        return this.href == url || url.href.indexOf(this.href) == 0;
    }).addClass('active').parent().parent().addClass('in').parent();
    if (element.is('li')) {
        element.addClass('active');
    }
});

/*
  刷新当前页面
*/
function Reload() {
    location.reload();
    return false;
}

/*
 href跳转页面
*/
function Urlhref(url) {
    location.href = url;
    return false;
}

/**
获取选中复选框值
值：1,2,3,4
**/
function CheckboxValue() {
    var reVal = '';
    $('[type = checkbox]').each(function () {
        if ($(this).attr("checked")) {
            reVal += $(this).val() + ",";
        }
    });
    reVal = reVal.substr(0, reVal.length - 1);
    return reVal;
}
/**
文本框只允许输入数字
**/
function IsNumber(obj) {
    $("#" + obj).bind("contextmenu", function () {
        return false;
    });
    $("#" + obj).css('ime-mode', 'disabled');
    $("#" + obj).keypress(function (e) {
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            return false;
        }
    });
}
/**
只能输入数字和小数点
**/
function IsMoney(obj) {
    $("#" + obj).bind("contextmenu", function () {
        return false;
    });
    $("#" + obj).css('ime-mode', 'disabled');
    $("#" + obj).bind("keydown", function (e) {
        var key = window.event ? e.keyCode : e.which;
        if (isFullStop(key)) {
            return $(this).val().indexOf('.') < 0;
        }
        return (isSpecialKey(key)) || ((isNumber(key) && !e.shiftKey));
    });
    function isNumber(key) {
        return key >= 48 && key <= 57
    }
    function isSpecialKey(key) {
        return key == 8 || key == 46 || (key >= 37 && key <= 40) || key == 35 || key == 36 || key == 9 || key == 13
    }
    function isFullStop(key) {
        return key == 190 || key == 110;
    }
}

/**
* 金额格式(保留2位小数)后格式化成金额形式
*/
function FormatCurrency(num) {
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3) ; i++)
        num = num.substring(0, num.length - (4 * i + 3)) + '' +
                num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + num + '.' + cents);
}

//保留两位小数    
//功能：将浮点数四舍五入，取小数点后2位   
function ToDecimal(x) {
    var f = parseFloat(x);
    if (isNaN(f)) {
        return 0;
    }
    f = Math.round(x * 100) / 100;
    return f;
}

/**
查找数组中是否存在某个值
arr:数组
val:对象值
**/
function ArrayExists(arr, val) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == val)
            return true;
    }
    return false;
}

/* 
请求Ajax 返回文本类型
*/
function GetAjax(url, postData, callBack) {
	$.ajax({
	   type: 'post',
	   dataType: "text",
	   url: RootPath() + url,
	   data: postData,
	   cache: false,
	   async: false,
	   success: function (data) {
	       callBack(data);
	   },
	   error: function (data) {
		   AlertDialog("error:" + JSON.stringify(data));
	   }
	});
}

/* 
请求Ajax 返回json格式
*/
function AjaxJson(url, postData, callBack) {
	try {
	   $.ajax({
	       url: url,
	       type: "post",
	       data: postData,
	       dataType: "json",
	       async: false,
	       success: function (data) {
	    	   callBack(data);
	       },
	       error: function () {
	    	   TipDialog('ajax 服务器请求失败！', 0);
	       }
	   });
	} catch (e) {
		TipDialog('ajax 服务器请求失败！', 0);
	}
}

/**
* 获取搜索条件：返回JSON
* var parameter = GetParameterJson("搜索区域table的ID");
*/
function GetParameterJson(tableId) {
    var parameter = "";
    $("#" + tableId + " tr").find('td').find('input,select').each(function () {
        var pk_id = $(this).attr('id');
        var pk_value = $("#" + pk_id).val();
        parameter += '"' + pk_id + '"' + ':' + '"' + $.trim(pk_value) + '",'
    });
    parameter = parameter.substr(0, parameter.length - 1);
    return '{' + parameter + '}';
}

/*
 * 关闭对话框
 */
function CloseDialog(dialogID) {
	try {
		$.dialog.list[dialogID].close();
	} catch (e) {
	}
}

/*
 * 锁屏操作
 */
function lock(message) {
	var msg = "数据加载中...";
	$.dialog.tips((!!message ? message: msg), 200, 'loading.gif').lock();
}

/*
 * 解锁屏操作
 */
function unlock() {
	try {
		$.dialog.list.Tips.close();
	} catch (e) {
	}
}

/**
	短暂提示
	msg: 显示消息
	time：停留时间
	type：类型 ：成功，=1：失败 = 0，其他：警告
**/
function TipDialog(msg, time, type) {
    var msg = "<div class='ui_alert_tip'>" + msg + "</div>"
    if (type == 0) {
        $.dialog.tips(msg, time, 'fail.png');
    } else if (type == 1) {
        $.dialog.tips(msg, time, 'succ.png');
    } else {
        $.dialog.tips(msg, time, 'i.png');
    }
}

/*
弹出对话框（带：确认按钮、取消按钮）
*/
function OpenDialog(url, _id, _title, _width, _height, callBack) {
    top.$.dialog({
        id: _id,
        width: _width,
        height: _height,
        max: false,
        min: false,
        lock: true,
        title: _title,
        resize: false,
        extendDrag: true,
        content: 'url:' + RootPath() + url,
        ok: function () {
            callBack(_id);
            return false;
        },
        cancel: true
    });
}

/*
弹出对话框（带：确认按钮、取消按钮）
*/
function OpenDialogHtml(html, _id, _title, _width, _height, callBack) {
    $.dialog({
        id: _id,
        width: _width,
        height: _height,
        max: false,
        min: false,
        lock: true,
        title: _title,
        resize: false,
        extendDrag: true,
        content: html,
        ok: function () {
            callBack(_id);
            return false;
        },
        cancel: true
    });
}

/*
最大化弹出对话框（带：确认按钮、取消按钮）
*/
function FullOpenDialog(url, _id, _title, callBack) {
    $.dialog({
        id: _id,
        lock: true,
        title: _title,
        max: false,
        min: false,
        width: $(window).width() - 40,
        height: $('body').height() - 100,
        content: 'url:' + RootPath() + url,
        ok: function () {
            callBack(_id);
            return false;
        },
        cancel: true
    })
}
/*
弹出对话框（没按钮）
*/
function Dialog(url, _id, _title, _width, _height) {
    $.dialog({
        id: _id,
        width: _width,
        height: _height,
        max: false,
        lock: true,
        title: _title,
        content: 'url:' + RootPath() + url
    });
}
/*
最大化弹出对话框（没按钮）
*/
function FullDialog(url, _id, _title) {
    $.dialog({
        id: _id,
        lock: true,
        title: _title,
        max: false,
        min: false,
        width: $(window).width() - 40,
        height: $('body').height() - 100,
        content: 'url:' + RootPath() + url
    })
}

/*
   查询查询对话框
*/
function QueryDialog(url, _id, _title, _width, _height, _callBack) {
    $.dialog({
        id: _id,
        width: _width,
        height: _height,
        max: false,
        mix: false,
        lock: true,
        title: _title,
        content: 'url:' + RootPath() + url,
        button: [
            {
                name: '查 询',
                callback: function () {
                    _callBack(_id);
                    return false;
                }
            },
            {
                name: '取 消'
            }
        ]
    });
}

/*
警告消息
title: 提示消息
msg: 显示消息
type：类型 ：成功，=1：失败 =0，其他：警告
*/
function AlertDialog(title, msg, type) {
	var msg = "<div class='ui_alert'>" + msg + "</div>"
    var icon = "";
    if (type == 1) {
        icon = "succ.png";
    } else if (type == 0) {
        icon = "fail.png";
    } else {
        icon = "i.png";
    }
    
    $.dialog({
        id: "AlertDialog",
        icon: icon,
        content: msg,
        title: ((!!title) ? title : "系统提示"),
        ok: function () {
            return true;
        }
    });
}
/*
确认对话框
_title: 标题
msg: 消息内容
callBack: 回调函数
*/
function ConfirmDialog(_title, msg, callBack) {
    var msg = "<div class='confirm-dialog'>" + $.trim(msg) + "</div>"
    $.dialog({
        id: "ConfirmDialog",
        lock: true,
        icon: "hits.png",
        content: msg,
        title: _title,
        width:300,
        height:100,
        ok: function () {
            callBack(true)
            return true;
        },
        cancel: function () {
            callBack(false)
            return true;
        }
    });
}

/*打开网页 window.open
/*url:          表示请求路径
/*windowname:   定义页名称
/*width:        宽度
/*height:       高度
---------------------------------------------------*/
function OpenWindow(url, title, w, h) {
    var width = w;
    var height = h;
    var left = ($(window).width() - width) / 2;
    var top = ($(window).height() - height) / 2;
    window.open(RootPath() + url, title, 'height=' + height + ', width=' + width + ', top=' + top + ', left=' + left + ', toolbar=no, menubar=no, scrollbars=no, resizable=false, location=no, status=no, titlebar=no, alwaysRaised=yes');
}
/*弹出对话框end========================================*/

//js获取网站根路径(站点及虚拟目录)
function RootPath() {
    var strFullPath = window.document.location.href;
    var strPath = window.document.location.pathname;
    var pos = strFullPath.indexOf(strPath);
    var prePath = strFullPath.substring(0, pos);
    var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
    return (prePath + postPath);
}

//获取系统Platform
function GetSystemCtxPath() {
    if($("#ctxPath").length > 0) {
      return $("#ctxPath").val();
    }
    return "";
}

/**
 * 保存和更新共通操作
 */
function saveOrUpdateHandle(openDialogUrl, _title, _width, _height, addOrUpdUrl) {
	var projectName = PorjectUtil.getProjectName();
	if(addOrUpdUrl.indexOf(projectName)<0){
		addOrUpdUrl = projectName + addOrUpdUrl;
	}
	//添加用户
	OpenDialog(openDialogUrl, "addOrUpdFormDialog", _title, _width, _height, function(iframe) {
		//验证Valid Form
		frames[iframe].ValidForm();
		//判断验证
		if(frames[iframe].IsVaild()) {
			lock('数据正在保存,请稍等...');
			//更新数据
			AjaxJson(addOrUpdUrl, frames[iframe].GetFormData(), function(data) {
				//解锁
				unlock();
				if (data.flag == 'success') {
					  //关闭Dialog
					  CloseDialog("addOrUpdFormDialog");
					  //msg, time, type[1-success, 0-fail, other];
					  TipDialog(data.message, 1, 1);
					  //刷新表格
					  table.submit();
					} 
				else {
					TipDialog(data.message, 1, 0);
				}	
		   });
		}
	});
}


